/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.legendshop.oa.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.EventTypeEnum;
import com.legendshop.oa.constants.FunctionEnum;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.constants.ProjectStatusEnum;
import com.legendshop.oa.constants.TaskStatusEnum;
import com.legendshop.oa.dto.AjaxTaskListResultDto;
import com.legendshop.oa.dto.EventQueryDto;
import com.legendshop.oa.dto.TaskAssignDto;
import com.legendshop.oa.dto.TaskCancelDto;
import com.legendshop.oa.dto.TaskCloseDto;
import com.legendshop.oa.dto.TaskEstimateDto;
import com.legendshop.oa.dto.TaskFinishDto;
import com.legendshop.oa.dto.TaskQueryDto;
import com.legendshop.oa.dto.TaskStartDto;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.model.AdminUser;
import com.legendshop.oa.model.Project;
import com.legendshop.oa.model.Task;
import com.legendshop.oa.model.TaskEstimate;
import com.legendshop.oa.model.UserEvent;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.pages.BackPage;
import com.legendshop.oa.pages.RedirectPage;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.permission.service.AdminUserService;
import com.legendshop.util.AppUtils;
import com.legendshop.util.DateUtil;
import com.legendshop.util.JSONUtil;

/**
 * The Class TaskController 控制器
 */
@Controller
@RequestMapping("/admin/task")
public class TaskController extends BaseController {

	/** The log. */
	private final static Logger log = LoggerFactory.getLogger(TaskController.class);

	@Autowired
	private TaskService taskService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private EventService eventService;

	@Autowired
	private TaskEstimateService taskEstimateService;

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private ProjectMemberService projectMemberService;

	/**
	 * 项目下的列表查询
	 */
	@RequestMapping("/query/{projectId}")
	public String queryProjectTask(HttpServletRequest request, HttpServletResponse response,
			@PathVariable Long projectId) {
		UserDetail userDetail = UserManager.getUser(request);
		Project project = projectService.getProject(userDetail, projectId);
		request.setAttribute("project", project);

		return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_TASK_LIST_PAGE);
	}
	
	
	
	/**
	 * 项目下的看板
	 */
	@RequestMapping("/dashboard/{projectId}")
	public String dashboard(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId) {
		UserDetail userDetail = UserManager.getUser(request);
		Project project = projectService.getProject(userDetail, projectId);
		request.setAttribute("project", project);
		
		return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_DASHBOARD_PAGE);
	}
	
	/**
	 * 项目下的列表查询
	 */
	@RequestMapping("/dashboardTask/{projectId}")
	public String dashboardTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId,TaskQueryDto taskQueryDto) {
		taskQueryDto.setProjectId(projectId);
		taskQueryDto.setPageSize(10000);//最多加载10000条
		UserDetail ud = UserManager.getUser(request);
		taskQueryDto.setUserName(ud.getUsername());
		PageSupport<Task> ps = taskService.getTask(taskQueryDto);
//		PageSupportHelper.savePage(request, ps);
//
//		request.setAttribute("taskQueryDto", taskQueryDto);
		
		List<Task> unstartList = new ArrayList<>(); //未开始
		List<Task> processingList = new ArrayList<>(); //进行中
		List<Task> finishList = new ArrayList<>(); //已完成
		List<Task> closeList = new ArrayList<>(); //已关闭
		List<Task> cancelList = new ArrayList<>(); //已取消
				
		for (Task task : ps.getResultList()) {
			if(TaskStatusEnum.UNSTART.value().equals(task.getStatus())){
				unstartList.add(task);
			}else if(TaskStatusEnum.PROCESSING.value().equals(task.getStatus())){
				processingList.add(task);
			}else if(TaskStatusEnum.FINISH.value().equals(task.getStatus())){
				finishList.add(task);
			}else if(TaskStatusEnum.CLOSE.value().equals(task.getStatus())){
				closeList.add(task);
			}else if(TaskStatusEnum.CANCEL.value().equals(task.getStatus())){
				cancelList.add(task);
			}
		}
		request.setAttribute("unstartList", unstartList);
		request.setAttribute("processingList", processingList);
		request.setAttribute("finishList", finishList);
		request.setAttribute("closeList", closeList);
		request.setAttribute("cancelList", cancelList);
		
		return PathResolver.getPath(request, response, BackPage.PROJECT_DASHBOARD_LIST_PAGE);
	}
	
	/**
	 * 项目下的列表查询
	 */
	@RequestMapping("/queryContent/{projectId}")
	public String queryContent(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId, TaskQueryDto taskQueryDto) {
		taskQueryDto.setProjectId(projectId);
		if (taskQueryDto.getName() != null) {
			taskQueryDto.setName(taskQueryDto.getName().trim());// 去掉空格
		}
		UserDetail ud = UserManager.getUser(request);
		taskQueryDto.setUserName(ud.getUsername());
		PageSupport<Task> ps = taskService.getTask(taskQueryDto);
		PageSupportHelper.savePage(request, ps);

		Double leftHours = 0d; // 剩余时间
		Double totalConsumed = 0d;// 任务总消耗
		if (AppUtils.isNotBlank(ps.getResultList())) {
			for (Task task : ps.getResultList()) {

				if (task.getLeftHours() != null) {
					leftHours = leftHours + task.getLeftHours();
				}

				if (task.getTotalConsumed() != null) {
					totalConsumed = totalConsumed + task.getTotalConsumed();
				}
			}
		}
		request.setAttribute("leftHours", leftHours);
		request.setAttribute("totalConsumed", totalConsumed);
		request.setAttribute("taskQueryDto", taskQueryDto);
		return PathResolver.getPath(request, response, BackPage.PROJECT_TASK_CONTENT_LIST_PAGE);
	}

	/**
	 * 项目下的列表查询
	 */
	@RequestMapping(value = "/queryContentData/{projectId}")
	@ResponseBody
	public AjaxTaskListResultDto<Task> queryContentData(HttpServletRequest request, HttpServletResponse response,
			@PathVariable Long projectId, TaskQueryDto taskQueryDto) {
		return queryContentData(request, projectId, taskQueryDto);
	}

	/**
	 * 查询所有的任务
	 * 
	 * @param request
	 * @param response
	 * @param taskQueryDto
	 * @return
	 */
	@RequestMapping(value = "/queryContentData")
	@ResponseBody
	public AjaxTaskListResultDto<Task> queryAllTaskContentData(HttpServletRequest request, HttpServletResponse response, TaskQueryDto taskQueryDto) {

		return queryContentData(request, taskQueryDto.getProjectId(), taskQueryDto);
	}

	private AjaxTaskListResultDto<Task> queryContentData(HttpServletRequest request,Long projectId, TaskQueryDto taskQueryDto) {
		taskQueryDto.setProjectId(projectId);
		if (taskQueryDto.getName() != null) {
			taskQueryDto.setName(taskQueryDto.getName().trim());// 去掉空格
		}

		UserDetail ud = UserManager.getUser(request);
		taskQueryDto.setUserName(ud.getUsername());

		PageSupport<Task> ps = taskService.getTask(taskQueryDto);
		AjaxTaskListResultDto<Task> dto = new AjaxTaskListResultDto<Task>();
		if(projectId != null && !projectMemberService.isMemberInProject(ud.getUsername(), projectId)){
			dto.setMsg("不在项目里，如果要查看该项目的目标，请联系管理员先加入项目!");
			dto.setStatus(-1);
			return dto;
		}

		Double leftHours = 0d; // 剩余时间
		Double totalConsumed = 0d;// 任务总消耗
		if (AppUtils.isNotBlank(ps.getResultList())) {
			for (Task task : ps.getResultList()) {
				if(task.getCreateTime() != null){
					task.setCreateTimeStr(DateUtil.DateToString(task.getCreateTime(),"yyyy-MM-dd"));
				}
				if(task.getDeadline() != null){
					task.setDeadlineStr(DateUtil.DateToString(task.getDeadline(), "yyyy-MM-dd"));
				}
				if (task.getLeftHours() != null) {
					leftHours = leftHours + task.getLeftHours();
				}
				if (task.getTotalConsumed() != null) {
					totalConsumed = totalConsumed + task.getTotalConsumed();
				}
			}
		}



		dto.setLeftHours(leftHours);
		dto.setTotalConsumed(totalConsumed);
		dto.setResultList(ps.getResultList());
		dto.setTotal(ps.getTotal());
		dto.setMsg("成功");
		dto.setStatus(200);
		return dto;
	}

	/**
	 * 项目下所有的任务的列表查询
	 */
	@RequestMapping("/queryContent")
	public String queryAllProjectContentTask(HttpServletRequest request, HttpServletResponse response,
			TaskQueryDto taskQueryDto) {
		if (taskQueryDto.getName() != null) {
			taskQueryDto.setName(taskQueryDto.getName().trim());// 去掉空格
		}

		UserDetail ud = UserManager.getUser(request);
		taskQueryDto.setUserName(ud.getUsername());

		PageSupport<Task> ps = taskService.getTask(taskQueryDto);
		PageSupportHelper.savePage(request, ps);

		request.setAttribute("queryAllTask", taskQueryDto.isQueryAllTask());

		Double leftHours = 0d; // 剩余时间
		Double totalConsumed = 0d;// 任务总消耗
		if (AppUtils.isNotBlank(ps.getResultList())) {
			for (Task task : ps.getResultList()) {

				if (task.getLeftHours() != null) {
					leftHours = leftHours + task.getLeftHours();
				}

				if (task.getTotalConsumed() != null) {
					totalConsumed = totalConsumed + task.getTotalConsumed();
				}
			}
		}

		request.setAttribute("leftHours", leftHours);

		request.setAttribute("totalConsumed", totalConsumed);

		return PathResolver.getPath(request, response, BackPage.PROJECT_TASK_CONTENT_LIST_PAGE);
	}

	/**
	 * 项目下的工时
	 */
	@RequestMapping("/taskEstimate/{taskId}")
	public String taskEstimate(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);

		Task task = taskService.getTask(userDetail, taskId);
		request.setAttribute("task", task);
//采用异步的
//		List<TaskEstimate> taskEstimateList = taskEstimateService.getTaskEstimateByTask(taskId);
//		request.setAttribute("taskEstimateList", taskEstimateList);

		return PathResolver.getPath(request, response, BackPage.TASK_ESTIMATE_LIST_PAGE);
	}
	
	
	/**
	 * 项目下的工时,有分页内容
	 */
	@RequestMapping("/loadTaskEstimate/{taskId}")
	public String loadTaskEstimate(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId, String curPageNO) {
		PageSupport<TaskEstimate> ps = taskEstimateService.getTaskEstimateByTask(taskId, curPageNO);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("taskId", "taskId");
		return PathResolver.getPath(request, response, BackPage.TASK_ESTIMATE_PAGE);
	}

	
	/**
	 * 每日的工时 date: 日期
	 */
	@RequestMapping("/taskEstimateByDay/{date}")
	public String taskEstimateByDay(HttpServletRequest request, HttpServletResponse response, @PathVariable String date, String userName) {
//		Date date1 = DateUtil.StringToDate(date, "yyyy-MM-dd");
//		String userName1;
//		if (AppUtils.isNotBlank(userName) && !userName.equals("null") && !userName.equals("undefined")) {
//			userName1 = userName;
//		} else {
//			UserDetail ud = UserManager.getUser(request);
//			userName1 = ud.getUsername();
//		}

		//采用异步的
//		List<TaskEstimate> taskEstimateList = taskEstimateService.getTaskEstimateByDay(date1, userName1);
//		request.setAttribute("taskEstimateList", taskEstimateList);

		request.setAttribute("taskDate", date);
		
		UserDetail ud = UserManager.getUser(request);
		if(AppUtils.isNotBlank(userName) && !userName.equals("null") && !userName.equals("undefined")){
			if(!userName.equals(ud.getUsername())){//如果不是自己的账号登录,则把增加增加的任务隐藏掉
				request.setAttribute("differentUser", true);
			}
		}
		request.setAttribute("userName", userName);

		return PathResolver.getPath(request, response, BackPage.TASK_ESTIMATE_BY_DAY_LIST_PAGE);
	}
	
	
	/**
	 * 在日志视图下,项目下的工时,有分页内容
	 */
	@RequestMapping("/loadTaskEstimateByDay/{date}")
	public String loadTaskEstimateByDay(HttpServletRequest request, HttpServletResponse response, @PathVariable String date, String userName, String curPageNO) {
		Date date1 = DateUtil.StringToDate(date, "yyyy-MM-dd");
		String userName1;
		if (AppUtils.isNotBlank(userName) && !userName.equals("null") && !userName.equals("undefined")) {
			userName1 = userName;
		} else {
			UserDetail ud = UserManager.getUser(request);
			userName1 = ud.getUsername();
		}
		
		PageSupport<TaskEstimate> ps = taskEstimateService.getTaskEstimateByDay(date1, userName1, curPageNO);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("taskDate", date);
		return PathResolver.getPath(request, response, BackPage.TASK_ESTIMATE_PAGE);
	}
	
	

	/**
	 * 保存任务工时
	 */
	@RequestMapping(value = "/saveTaskEstimate/{taskId}")
	@ResponseBody
	public String saveTaskEstimate(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId,
			String taskEstimateDto) {
		UserDetail ud = UserManager.getUser(request);
		List<TaskEstimateDto> taskEstimateList = JSONUtil.getArray(taskEstimateDto, TaskEstimateDto.class);
		Task task = taskService.getTask(ud, taskId);

		//检查是否在项目里
		//boolean isInProject = projectMemberService.isMemberInProject(ud.getUsername(),task.getProjectId());
		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "noIn";// 失败
		}

		Project project = task.getProject();
		if (ProjectStatusEnum.PROCESSING.value().equals(project.getStatus())
				|| ProjectStatusEnum.DELAY.value().equals(project.getStatus())
				|| TaskStatusEnum.PROCESSING.value().equals(task.getStatus())) {
			boolean result = taskService.saveTaskEstimate(task, taskEstimateList, ud);
			if (result) {
				return "success";
			} else {
				log.warn("assign user failed");
				return "fail";// 失败
			}
		} else {
			return "statusError";
		}

	}

	/**
	 * 按天保存任务工时
	 */
	@RequestMapping(value = "/saveTaskEstimateByDay/{date}")
	@ResponseBody
	public String saveTaskEstimateByDay(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String date, String taskEstimateDto) {
		UserDetail ud = UserManager.getUser(request);

		Date date1 = DateUtil.StringToDate(date, "yyyy-MM-dd");

		List<TaskEstimateDto> taskEstimateList = JSONUtil.getArray(taskEstimateDto, TaskEstimateDto.class);
		if (AppUtils.isNotBlank(taskEstimateList)) {
			// 设置时间
			for (TaskEstimateDto te : taskEstimateList) {
				te.setDate(date1);
			}

			for (TaskEstimateDto te : taskEstimateList) {
				Long taskId = te.getTaskId();
				if(taskId == null){//没有选择任务，则直接新建
					Task task = new Task();
					task.setProjectId(te.getProjectId());
					Project project = projectService.getProject(ud, te.getProjectId());
					if(project != null){
						if (ProjectStatusEnum.PROCESSING.value().equals(project.getStatus())
								|| ProjectStatusEnum.DELAY.value().equals(project.getStatus())
								|| TaskStatusEnum.PROCESSING.value().equals(task.getStatus())) {


							Project project1 = projectService.getProject(ud, task.getProjectId());
							if(project1 == null){
								//不在項目里不能填写工时
								return "noIn";// 失败
							}

							boolean result = taskService.saveTaskEstimate(task, te, ud);
							log.warn("saveTaskEstimate result {}", result);
						} else {
							throw new BusinessException("saveTaskEstimateByDay error");
						}
					}
				}else{
					Task task = taskService.getTask(ud, te.getTaskId());
					Project project = task.getProject();
					if(project != null){
						if (ProjectStatusEnum.PROCESSING.value().equals(project.getStatus())
								|| ProjectStatusEnum.DELAY.value().equals(project.getStatus())
								|| TaskStatusEnum.PROCESSING.value().equals(task.getStatus())) {

							Project project1 = projectService.getProject(ud, task.getProjectId());
							if(project1 == null){
								//不在項目里不能填写工时
								return "noIn";// 失败
							}


							boolean result = taskService.saveTaskEstimate(task, te, ud);
							log.warn("saveTaskEstimate result {}", result);
						} else {
							throw new BusinessException("saveTaskEstimateByDay error");
						}
					}
				}

			}
		}

		return "success";

	}

	/**
	 * 列表查询 是否启用我的任务
	 */
	@RequestMapping("/query")
	public String query(HttpServletRequest request, HttpServletResponse response, TaskQueryDto taskQueryDto, String myTask) {
		if (taskQueryDto.getName() != null) {
			taskQueryDto.setName(taskQueryDto.getName().trim());// 去掉空格
		}

		UserDetail userDetail = UserManager.getUser(request);
		if (taskQueryDto.getProjectId() != null) {
			Project project = projectService.getProject(userDetail, taskQueryDto.getProjectId());
			request.setAttribute("project", project);

		}

		if (AppUtils.isNotBlank(myTask)) {
			taskQueryDto.setAssignedto(userDetail.getUsername());

			AdminUser adminUser = adminUserService.getAdminUserByUserName(userDetail.getUsername());
			if (adminUser != null) {
				taskQueryDto.setAssignedtoRealName(adminUser.getRealName());
			}

		}

		taskQueryDto.setQueryAllTask(true);
		request.setAttribute("taskQueryDto", taskQueryDto);

		return PathResolver.getPath(request, response, AdminTilesPage.ALL_TASK_LIST_PAGE);
	}

	/**
	 * 列表已经完成的任务
	 */
	@RequestMapping("/queryFinish/{projectId}")
	public String queryFinish(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId,
			TaskQueryDto taskQueryDto) {
		UserDetail userDetail = UserManager.getUser(request);
		Project project = projectService.getProject(userDetail, projectId);
		request.setAttribute("project", project);

		taskQueryDto.setUserName(userDetail.getUsername());

		taskQueryDto.setProjectId(project.getId());
		taskQueryDto.setStatus(TaskStatusEnum.FINISH.value());
		PageSupport<Task> ps = taskService.getTask(taskQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("taskQueryDto", taskQueryDto);

		return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_FINISH_TASK_LIST_PAGE);
	}

	/**
	 * 保存任务
	 * nextStep: 下一步是什么
	 */
	@RequestMapping(value = "/save")
	public String save(HttpServletRequest request, HttpServletResponse response, String nextStep, Task task) {
		UserDetail ud = UserManager.getUser(request);

		//检查是否在项目里
		boolean isInProject = projectMemberService.isMemberInProject(ud.getUsername(),task.getProjectId());
		if(!ud.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA) && !isInProject){
			//不在項目里不能填写工时
			return "fail";// 失败
		}

		Task savedTask = taskService.saveTask(task, ud);
		if (savedTask == null) {
			throw new BusinessException("save task error");
		}
		saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));

		if(nextStep != null && nextStep.equals("next")){
			//继续保存下一个任务目标
			return PathResolver.getPath(request, response,
					RedirectPage.TASK_LOAD_BY_PROJECT_QUERY.getNativeValue() + "/" + task.getProjectId(),
					RedirectPage.VARIABLE);
		}


		if (TaskStatusEnum.FINISH.value().equals(task.getStatus())) {
			return PathResolver.getPath(request, response,
					RedirectPage.TASK_FINISH_LIST_QUERY.getNativeValue() + "/" + task.getProjectId(),
					RedirectPage.VARIABLE);
		} else {
			return PathResolver.getPath(request, response,
					RedirectPage.TASK_LIST_QUERY.getNativeValue() + "/" + task.getProjectId(), RedirectPage.VARIABLE);
		}
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete/{id}")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		UserDetail userDetail = UserManager.getUser(request);

		Task task = taskService.getTask(userDetail, id);

		if(task == null){
			return "fail";
		}

		//检查是否在项目里
		boolean isInProject = projectMemberService.isMemberInProject(userDetail.getUsername(),task.getProjectId());
		if(!userDetail.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA) && !isInProject){
			//不在項目里不能填写工时
			return "fail";// 失败
		}


		if (task != null) {
			boolean deleteResult = taskService.deleteTask(task);
			// 日志已经评审过，无法删除
			if (!deleteResult) {
				return "fail";
			}
			saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("entity.deleted"));
		}

		return "success";
	}

	/**
	 * 删除,任务和日志分离,无需再判断任务
	 */
	@RequestMapping(value = "/deleteTaskEstimate/{taskEstimateId}")
	@ResponseBody
	public String deleteTaskEstimate(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskEstimateId) {
		   UserDetail userDetail = UserManager.getUser(request);
		   
		   TaskEstimate taskEstimate = taskEstimateService.getUnReviewedTaskEstimate(taskEstimateId);
		   
		   if(taskEstimate == null){
				log.warn("assign user failed");
				return "fail";// 失败
		   }
		   
			// 判断是否有VIEW_ALL_DATA权限，如果有，则加载所有的权限
			if (!UserManager.hasFunction(request, FunctionEnum.FUNCTION_VIEW_ALL_DATA.value())) {
				if(!userDetail.getUsername().equals(taskEstimate.getUserName())){
					log.warn("no right to delete");
					return "fail";// 失败
				}
			}
		   
			boolean result = taskEstimateService.deleteTaskEstimate(taskEstimate);
			if (result) {
				return "success";
			} else {
				log.warn("assign user failed");
				return "fail";// 失败
			}
	}

	/**
	 * 加载编辑页面
	 */
	@RequestMapping(value = "/loadByProject/{projectId}")
	public String loadByPro(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId, Long planId) {
		request.setAttribute("projectId", projectId);
		Project project = projectService.getProjectWithModule(projectId);
		request.setAttribute("project", project);

		if(planId != null){
			request.setAttribute("planId", planId);
		}

		return PathResolver.getPath(request, response, AdminTilesPage.TASK_EDIT_PAGE);
	}

	/**
	 * 分配任务
	 */
	@RequestMapping(value = "/assignTask/{taskId}")
	public String assignTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, taskId);
		if (task == null) {
			throw new BusinessException("Can not find task");
		}
		EventQueryDto eventQueryDto = new EventQueryDto();
		eventQueryDto.setRelateId(taskId);
		eventQueryDto.setType(EventTypeEnum.TASK.value());
		eventQueryDto.setPageSize(10);
		PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("task", task);
		return PathResolver.getPath(request, response, BackPage.ASSIGN_TASK_PAGE);
	}

	/**
	 * 开始任务
	 */
	@RequestMapping(value = "/startTask/{taskId}")
	public String startTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, taskId);
		if (task == null) {
			throw new BusinessException("Can not find task");
		}
		EventQueryDto eventQueryDto = new EventQueryDto();
		eventQueryDto.setRelateId(taskId);
		eventQueryDto.setType(EventTypeEnum.TASK.value());
		eventQueryDto.setPageSize(10);
		PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("task", task);
		return PathResolver.getPath(request, response, BackPage.START_TASK_PAGE);
	}

	/**
	 * 完成任务
	 */
	@RequestMapping(value = "/finishTask/{taskId}")
	public String finishTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, taskId);
		if (task == null) {
			throw new BusinessException("Can not find task");
		}
		EventQueryDto eventQueryDto = new EventQueryDto();
		eventQueryDto.setRelateId(taskId);
		eventQueryDto.setType(EventTypeEnum.TASK.value());
		eventQueryDto.setPageSize(10);
		PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("task", task);
		return PathResolver.getPath(request, response, BackPage.FINISH_TASK_PAGE);
	}

	/**
	 * 完成任务
	 */
	@RequestMapping(value = "/cancelTask/{taskId}")
	public String cancelTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, taskId);
		if (task == null) {
			throw new BusinessException("Can not find task");
		}
		EventQueryDto eventQueryDto = new EventQueryDto();
		eventQueryDto.setRelateId(taskId);
		eventQueryDto.setType(EventTypeEnum.TASK.value());
		eventQueryDto.setPageSize(10);
		PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("task", task);
		return PathResolver.getPath(request, response, BackPage.CANCEL_TASK_PAGE);
	}

	/**
	 * 关闭任务
	 */
	@RequestMapping(value = "/closeTask/{taskId}")
	public String closeTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, taskId);
		if (task == null) {
			throw new BusinessException("Can not find task");
		}
		EventQueryDto eventQueryDto = new EventQueryDto();
		eventQueryDto.setRelateId(taskId);
		eventQueryDto.setType(EventTypeEnum.TASK.value());
		eventQueryDto.setPageSize(10);
		PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("task", task);
		return PathResolver.getPath(request, response, BackPage.CLOSE_TASK_PAGE);
	}

	/**
	 * 分配任务
	 */
	@RequestMapping(value = "/assignUpdateTask/{taskId}")
	@ResponseBody
	public String assignUpdateTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId, TaskAssignDto taskAssignDto) {
		UserDetail ud = UserManager.getUser(request);
		Task task = taskService.getTask(ud, taskId);
		if(task == null){
			return "fail";
		}
		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "fail";// 失败
		}

		boolean result = taskService.assignUpdateTask(taskId, taskAssignDto, ud);
		if (result) {
			return "success";
		} else {
			log.warn("assign user failed");
			;
			return "fail";// 失败
		}

	}

	/**
	 * 开始任务
	 */
	@RequestMapping(value = "/startUpdateTask/{taskId}")
	@ResponseBody
	public String startUpdateTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId,
			TaskStartDto taskStartDto) {
		// 检查参数
		if (taskStartDto.getRealStarted() == null) {
			log.warn("RealStarted can not null");
			return "fail";// 失败
		}
		UserDetail ud = UserManager.getUser(request);


		Task task = taskService.getTask(ud, taskId);
		if(task == null){
			return "fail";
		}

		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "fail";// 失败
		}


		boolean result = taskService.startUpdateTask(taskId, taskStartDto, ud);
		if (result) {
			return "success";
		} else {
			log.warn("assign user failed");
			;
			return "fail";// 失败
		}

	}

	/**
	 * 开始任务
	 */
	@RequestMapping(value = "/finishUpdateTask/{taskId}")
	@ResponseBody
	public String finishUpdateTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId,
			TaskFinishDto taskFinishDto) {
		// 检查参数
		if (taskFinishDto.getFinishedDate() == null) {
			log.warn("FinishedDate can not null");
			return "fail";// 失败
		}
		if (taskFinishDto.getUserName() == null) {
			log.warn("UserName can not null");
			return "fail";// 失败
		}

		UserDetail ud = UserManager.getUser(request);


		Task task = taskService.getTask(ud, taskId);
		if(task == null){
			return "fail";
		}
		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "fail";// 失败
		}

		boolean result = taskService.finishUpdateTask(taskId, taskFinishDto, ud);
		if (result) {
			return "success";
		} else {
			log.warn("assign user failed");
			;
			return "fail";// 失败
		}

	}

	/**
	 * 取消任务
	 */
	@RequestMapping(value = "/cancelUpdateTask/{taskId}")
	@ResponseBody
	public String cancelUpdateTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId,
			TaskCancelDto taskCancelDto) {
		UserDetail ud = UserManager.getUser(request);

		Task task = taskService.getTask(ud, taskId);
		if(task == null){
			return "fail";
		}
		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "fail";// 失败
		}

		boolean result = taskService.cancelUpdateTask(taskId, taskCancelDto, ud);
		if (result) {
			return "success";
		} else {
			log.warn("assign user failed");
			;
			return "fail";// 失败
		}

	}

	/**
	 * 关闭任务
	 */
	@RequestMapping(value = "/closeUpdateTask/{taskId}")
	@ResponseBody
	public String closeUpdateTask(HttpServletRequest request, HttpServletResponse response, @PathVariable Long taskId,
			TaskCloseDto taskCloseDto) {

		UserDetail ud = UserManager.getUser(request);

		Task task = taskService.getTask(ud, taskId);
		if(task == null){
			return "fail";
		}
		Project project1 = projectService.getProject(ud, task.getProjectId());
		if(project1 == null){
			//不在項目里不能填写工时
			return "fail";// 失败
		}

		boolean result = taskService.closeUpdateTask(taskId, taskCloseDto, ud);
		if (result) {
			return "success";
		} else {
			log.warn("assign user failed");
			return "fail";// 失败
		}

	}

	/**
	 * 根据Id加载
	 */
	@RequestMapping(value = "/load/{id}")
	public String load(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		UserDetail userDetail = UserManager.getUser(request);
		Task task = taskService.getTask(userDetail, id);
		if (task != null) {
			request.setAttribute("task", task);
			request.setAttribute("planId", task.getPlanId()); //为了兼容其他页面的参数传递，因为其他页面没有这个task
			Project project = projectService.getProjectWithModule(task.getProjectId());
			request.setAttribute("project", project);

			EventQueryDto eventQueryDto = new EventQueryDto();
			eventQueryDto.setRelateId(id);
			eventQueryDto.setType(EventTypeEnum.TASK.value());
			eventQueryDto.setPageSize(256);
			PageSupport<UserEvent> ps = eventService.getEventPage(eventQueryDto);
			PageSupportHelper.savePage(request, ps);
		}

		return PathResolver.getPath(request, response, AdminTilesPage.TASK_EDIT_PAGE);
	}

	/**
	 * 加载编辑页面
	 */
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest request, HttpServletResponse response) {
		return PathResolver.getPath(request, response, AdminTilesPage.TASK_EDIT_PAGE);
	}

	/**
	 * 查询用户列表给select2使用
	 * 
	 * @param q
	 *            查询内容
	 * @param pageSize
	 *            每页大小
	 * @param currPage
	 *            当前页
	 * @param  projectId 当前的项目的Id
	 * @param  startDate 开始时间
	 * @param  endDate 结束时间
	 * @return
	 */
	@RequestMapping("/taskList")
	public @ResponseBody JSONObject taskList(HttpServletRequest request, String q, Integer pageSize, Integer currPage, Long projectId, Date startDate, Date endDate) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 300;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}
		UserDetail userDetail = UserManager.getUser(request);
		JSONObject result = taskService.queryList(projectId,startDate,endDate, userDetail.getUsername(), q, pageSize, currPage);
		return result;
	}
	
	
}
